import { useModel } from "umi";
import { useReactive } from "ahooks";

const useCategory = () => {
    const { remoteData } = useModel("global");
    const { organizationUuid } = useModel("organization.info");

    const state = useReactive({
        appLoading: false,
        submitLoading: false,
        applications: [],
        totalCount: 0,
        stateColor: {
            待上架: "#2db7f5",
            已上架: "#87d068",
            已下架: "#f50",
        },
    });

    const loadApplicationsByPage = async ({ order, page, pageSize, where }) => {
        state.appLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getAll",
            params: {
                aiSdud: organizationUuid,
                aiStat: "已上架",
                where: where || {},
                limit: pageSize,
                offset: (page - 1) * pageSize || 0,
                order: order || null,
            },
        });
        state.applications = res?.applications || [];
        state.totalCount = res?.totalCount || 0;
        state.appLoading = false;
    };

    const loadApplicationByShelfStatus = async (status) => {
        state.appLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getAll",
            params: {
                aiSdud: organizationUuid,
                aiStat: status,
            },
        });
        state.applications = res || [];
        state.appLoading = false;
        return state.applications;
    };

    const updateApplication = async (aiUuid, data, callback) => {
        state.submitLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/update",
            params: { aiUuid, data },
        });
        if (res) {
            callback && callback(res);
        }
        state.submitLoading = false;
    };

    const updateApplicationShelfState = async (aiUuids, status, callback) => {
        state.submitLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/batchShelfStatus",
            params: {
                aiSdud: organizationUuid,
                aiStat: status,
                aiPuti: new Date().getUTCTime(),
                aiUuids: aiUuids,
            },
        });
        if (res) {
            callback && callback(res);
        }
        state.submitLoading = false;
    };

    return { ...state, loadApplicationByShelfStatus, updateApplication, updateApplicationShelfState, loadApplicationsByPage };
};

export default useCategory;
